<?php
// +----------------------------------------------------------------------
// | sfadmin - Suifeng Administration
// +----------------------------------------------------------------------
// | Copyright (c) 2017-2020 http://suifeng.tech All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: suifeng <1787585212@qq.com>
// +----------------------------------------------------------------------

namespace app\wechat\controller\admin;

use app\wechat\common\AdminWxController;
use app\admin\common\AdminException;

class Menu extends AdminWxController
{
    public function index()
    {
        $data['menu_list'] = model('wechat/menu')->get_list_tree($this->mp_id, 0);
        $this->display('admin/menu/menu_list', $data);
    }

    public function create()
    {
        $menu_info = model('wechat/menu')->initDefault();

        if (request()->isPost()) {
            $menu_info->acceptData($this->post_array());

            if ($menu_info->save() !== false) {
                $this->success('新增成功。', $this->url('index'));
            }
        }

        $menu_info['mp_id'] = $this->mp_id;

        $data['menu_info'] = $menu_info;
        $data['menu_type_list'] = service('wechat/menu')->get_menu_type_list();
        $data['parent_list'] = model('wechat/menu')->get_array_tree($this->mp_id, 0, $menu_info['id']);
        $this->display('admin/menu/menu_form', $data);
    }

    public function modify($id)
    {
        $menu_info = model('wechat/menu')->findOrFail($id);
        $menu_info['content'] = helper('admin/json')->decode($menu_info['content']);

        if (request()->isPost()) {
            $menu_info->acceptData($this->post_array());

            if ($menu_info->save() !== false) {
                $this->success('修改成功。', $this->url('index'));
            }
        }

        $data['menu_info'] = $menu_info;
        $data['menu_type_list'] = service('wechat/menu')->get_menu_type_list();
        $data['parent_list'] = model('wechat/menu')->get_array_tree($this->mp_id, 0, $menu_info['id']);
        $this->display('admin/menu/menu_form', $data);
    }

    public function delete($id)
    {
        model('wechat/menu')->delete_recursion($id);
        $this->success('删除成功。', $this->url('index'));
    }

    public function upload()
    {
        try {
            service('wechat/menu')->upload_menu_to_wx($this->mp_id);
        } catch (AdminException $ex) {
            $this->error($ex->getMessage());
        }

        $this->success('菜单上传成功。', $this->url('index'));
    }
}